<?php

namespace frontend\modules\orders\controllers;

use frontend\modules\base\controllers\BaseController;
use frontend\modules\marketing\models\ShareReb;
use frontend\modules\orders\models\Cservice;
use frontend\modules\orders\models\CserviceImages;
use frontend\modules\orders\models\OrderInfo;
use Yii;
use frontend\modules\orders\models\OrderGoods;
use frontend\modules\orders\models\search\OrderGoodsSearch;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * 货物订单信息查询，货物订单生成。
 */
class OrdergoodsController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 获取用户售后列表
     * @desc
     *
     * @param string access_token |token|yes|32位
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionGetservice()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $cserviceARR = Cservice::find()
                    ->select('g.*,cs.*,oi.order_sn')
                    ->from('cservice AS cs')
                    ->leftJoin('order_goods AS og','cs.order_goods_id = og.rec_id')
                    ->leftJoin('order_info AS oi','oi.order_id = og.order_id')
                    ->leftJoin('goods AS g','g.goods_id = og.goods_id')
                    ->where(['cs.user_id'=>Yii::$app->UserInfo->userid])
                    ->where(['<>','cs.is_deal',-1])
                    ->asArray()
                    ->all();
                $message = ['code'=>200,'message'=>"获取售后列表成功",'data'=>$cserviceARR];
                return json_encode($message);
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 图片删除
     */
    public function actionDelimage()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $postData  = $this->post['data'];

                $cservice_images_id = $postData['cservice_images_id'];
                $cserviceImages = CserviceImages::findOne(['cservice_images_id'=>$cservice_images_id]);
                unlink(Yii::$app->basePath.$cserviceImages->cservice_images);
                $cserviceImages->delete();
                $message = ['code'=>200,'message'=>"图片删除成功",'data'=>[]];
                return json_encode($message);
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 添加售后
     * @desc
     *
     * @param string $data[content] |售后内容|yes|
     * @param string $data[cservice_type] |售后类型|yes|0:换货1：维修|
     * @param string $data[images] |维修换货图片|yes|
     * @param string $data[order_goods_id] |货品品ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCserviceadd()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];

        $cservice = Cservice::findOne(['order_goods_id'=>$postData['order_goods_id']]);
        if(!$cservice) {
            $cservice = new Cservice();
            $cservice->order_goods_id = $postData['order_goods_id'];
            $cservice->cservice_code = $this->createCode();
        }
        $cservice->cservice_type = $postData['cservice_type'];
        $cservice->content = $postData['content'];
        $cservice->is_deal = 0;
        $cservice->user_id = Yii::$app->UserInfo->userid;
        if($cservice->save()){
            $message = ['code'=>200,'message'=>'售后添加成功'];
            return  json_encode($message);
        }
        $message = ['code'=>500,'message'=>json_encode($cservice->errors)];
        return  json_encode($message);
    }

    /**
     * 创建订单号
     *
     * @return string
     */
    public function createCode()
    {
        $time = time();
        $sn = date("Ymdhis",$time).rand(1000,999);
        if(Cservice::findOne(['cservice_code'=>$sn])){
            $this->createCode();
        }
        return $sn;
    }

    /**
     * 图片上传
     * @desc
     *
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionUpload()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $post = $_POST;
                $imgStr =isset($post['imgStr'])?$post['imgStr']:'';
                $imgStr = str_replace(" ","+",$imgStr);
                $order_goods_id = isset($post['recid'])?$post['recid']:'';

                $baseUrl = Yii::$app->basePath;
                $webUrlBaseOnApp= '/web/upload/cservice/'.$order_goods_id.'/';
                $baseImages = $baseUrl.$webUrlBaseOnApp;
                is_dir($baseImages) OR mkdir($baseImages, 0777, true);

                $imageName = time().'-'.rand(10,1000).'.png';
                $finalPath = $baseImages.$imageName;

                if (!preg_match('/data:([^;]*);base64,(.*)/', $imgStr, $matches)) {
                    die("error");
                }

                $content = base64_decode($matches[2]);
                file_put_contents($finalPath,$content);

                $beginTransaction = Yii::$app->db->beginTransaction();
                try{
                    $cservice = Cservice::findOne(['order_goods_id'=>$order_goods_id]);
                    if($cservice) {
                        $cserviceImages = new CserviceImages();
                        $cserviceImages->cservice_images = $webUrlBaseOnApp.$imageName;
                        $cserviceImages->cservice_id = $cservice->cservice_id;
                        if(!$cserviceImages->save()){
                            throw new Exception(json_encode($cserviceImages->errors));
                        }
                    } else{
                        $cservice = new Cservice();
                        $cservice->user_id = Yii::$app->UserInfo->userid;
                        $cservice->order_goods_id = $order_goods_id;
                        $cservice->cservice_type = 0;
                        $cservice->is_deal = -1;
                        $cservice->content = '';
                        if(!$cservice->save()){
                            throw new Exception(json_encode($cservice->errors));
                        }

                        $cserviceImages = new CserviceImages();
                        $cserviceImages->cservice_images = $webUrlBaseOnApp.$imageName;
                        $cserviceImages->cservice_id = $cservice->cservice_id;
                        if(!$cserviceImages->save()){
                            throw new Exception(json_encode($cserviceImages->errors));
                        }
                    }
                    $beginTransaction->commit();
                    $message = ['code'=>200,'message'=>"图片上传成功",'data'=>$webUrlBaseOnApp.$imageName,'cservice_images_id'=>$cserviceImages->cservice_images_id];
                    return json_encode($message);
                } catch (Exception $e) {
                    $beginTransaction->rollBack();
                    $message = ['code'=>500,'message'=>$e->getMessage(),'data'=>[]];
                    return json_encode($message);
                }
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 获取该评论的评价图片
     * @desc 获取该评论的评价图片
     *
     * @param string data[rec_id] |货物rec_id|yes|40位|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionZoomcservice()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $rec_id = $postData['rec_id'];
        $imagesAR = CserviceImages::find()
            ->select('ci.*')
            ->from('cservice_images AS ci')
            ->leftJoin('cservice AS c','c.cservice_id = ci.cservice_id')
            ->leftJoin('order_goods AS og','og.rec_id = c.order_goods_id')
            ->where(['og.rec_id'=>$rec_id])
            ->asArray()
            ->All();
        $message = ['code'=>200,'message'=>"获取评价图片成功",'data'=>$imagesAR];
        return json_encode($message);
    }

    /**
     * 获取订单用户活动返利列表
     * @desc 获取订单用户活动返利列表
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionOrdershare()
    {
        $user_id =  Yii::$app->UserInfo->userid;
        $orderArr = OrderInfo::find()->andWhere(['user_id'=>$user_id,'pay_status'=>2])->asArray()->all();
//        $children = array();
        foreach($orderArr as $k=>$v) {
            $orderArr[$k]['joinUser'] = OrderGoods::find()
                ->select('u.tx_images,u.wx_name')
                ->from('order_goods as og')
                ->leftJoin('user as u','u.id=og.user_id')
                ->where(['re_ordersn'=>$v['order_sn']])
                ->asArray()
                ->all();
            $orderArr[$k]['ChooseOrderGood'] = OrderGoods::find()
                ->select('g.goods_name,g.goods_image,g.goods_desc,g.shop_price,g.attrText')
                ->from('order_goods as og')
                ->leftJoin('goods as g','g.goods_id=og.goods_id')
                ->where(['og.order_id'=>$v['order_id']])
                ->asArray()
                ->one();
        }
        $message = ['code'=>200,'message'=>"获取成功",'data'=>$orderArr];
        return json_encode($message);
    }

    /**
     * 获取单个订单用户活动返利列表详情
     * @desc 获取单个订单用户活动返利列表详情
     *
     * @param string data[order_sn] |订单号|yes|12位|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionUsershare()
    {
        $post = Yii::$app->request->post();
        if($post){
            $order_sn = isset($post['data']['order_sn'])?$post['data']['order_sn']:'';
        }
        $orderArr = array();
        if($order_sn){
            $orderArr['joinUser'] = OrderGoods::find()
                ->select('u.tx_images,u.wx_name,og.shop_price')
                ->from('order_goods as og')
                ->leftJoin('user as u','u.id=og.user_id')
                ->where(['re_ordersn'=>$order_sn])
                ->asArray()
                ->all();

            $order_id = OrderInfo::findOne(['order_sn'=>$order_sn])->order_id;
            $orderArr['ChooseOrderGood'] = OrderGoods::find()
                ->select('g.goods_name,g.goods_image,g.goods_desc,g.shop_price,g.attrText')
                ->from('order_goods as og')
                ->leftJoin('goods as g','g.goods_id=og.goods_id')
                ->where(['og.order_id'=>$order_id])
                ->asArray()
                ->all();

            $message = ['code'=>200,'message'=>"获取成功",'data'=>$orderArr];
            return json_encode($message);
        }

    }

}
